package com.stylefeng.guns.modular.customer.controller;

import cn.afterturn.easypoi.entity.vo.NormalExcelConstants;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.base.tips.SuccessTip;
import com.stylefeng.guns.core.common.annotion.Permission;
import com.stylefeng.guns.core.common.constant.Const;
import com.stylefeng.guns.core.common.constant.factory.PageFactory;
import com.stylefeng.guns.core.common.exception.BizExceptionEnum;
import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.core.support.BeanKit;
import com.stylefeng.guns.core.support.VlidationUtil;
import com.stylefeng.guns.modular.customer.dao.PurchaseDao;
import com.stylefeng.guns.modular.customer.service.IPurchaseService;
import com.stylefeng.guns.modular.customer.transfer.PurchaseXlsM;
import com.stylefeng.guns.modular.customer.util.CustomerUtil;
import com.stylefeng.guns.modular.customer.warpper.PurchaseWrapper;
import com.stylefeng.guns.modular.customer.warpper.SaleWrapper;
import com.stylefeng.guns.modular.system.model.Purchase;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.flowable.bpmn.model.DataGrid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.naming.NoPermissionException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;


/**
 * 采购配套控制器
 *
 * @author fengshuonan
 * @Date 2018-04-03 15:02:21
 */
@Controller
@RequestMapping("/purchase")
public class PurchaseController extends BaseController {

    private String PREFIX = "/customer/purchase/";

    @Autowired
    private IPurchaseService purchaseService;

    @Autowired
    private PurchaseDao purchaseDao;

    /**
     * 跳转到采购配套首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "purchase.html";
    }

    /**
     * 跳转到添加采购配套
     */
    @RequestMapping("/purchase_add")
    public String purchaseAdd() {
        return PREFIX + "purchase_add.html";
    }

    /**
     * 跳转到修改采购配套
     */
    @RequestMapping("/purchase_update/{purchaseId}")
    public String purchaseUpdate(@PathVariable Integer purchaseId, Model model) {
        Purchase purchase = purchaseService.selectById(purchaseId);
        Map<String, Object> map = BeanKit.beanToMap(purchase);
        model.addAttribute("item", new PurchaseWrapper(map).warp());
        LogObjectHolder.me().set(purchase);
        return PREFIX + "purchase_edit.html";
    }

    /**
     * 获取采购配套列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(
            @RequestParam(value = "customerCompanyId", required = false) Integer customerCompanyId,
            @RequestParam(value = "customerCompanyName", required = false) String customerCompanyName) {
        Page<Purchase> page = new PageFactory<Purchase>().defaultPage();
        List<Map<String, Object>> result = purchaseService.selectPurchasePage(page, customerCompanyId, customerCompanyName);
        page.setRecords((List<Purchase>) new SaleWrapper(result).warp());
        return super.packForBT(page);
    }

    /**
     * 新增采购配套
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    @Permission
    @ApiOperation(value = "新增采购配套", tags = "采购配套", httpMethod = "POST", code = 200, response = SuccessTip.class)
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name = "year", value = "年度", dataType = "int", required = true),
                    @ApiImplicitParam(name = "providerName", value = "供应商名称", dataType = "string", required = true),
                    @ApiImplicitParam(name = "customerCompanyId", value = "客户id", dataType = "integer", required = true),
                    @ApiImplicitParam(name = "product", value = "product", dataType = "string", required = true),
                    @ApiImplicitParam(name = "annualPurchaseAmount", value = "年度采购金额", dataType = "Float", required = true),
                    @ApiImplicitParam(name = "accountPayableBalance", value = "应付账款余额", dataType = "Float", required = false),
                    @ApiImplicitParam(name = "cashPaid", value = "现金付款量", dataType = "Float", required = false),
                    @ApiImplicitParam(name = "silverTicketPaid", value = "银票付款量", dataType = "Float", required = false),
                    @ApiImplicitParam(name = "businessTicketPaid", value = "商票付款量", dataType = "Float", required = false),
                    @ApiImplicitParam(name = "period", value = "一般期限", dataType = "Float", required = false),
                    @ApiImplicitParam(name = "businessTicketDiscount", value = "商票贴现量", dataType = "Float", required = false),
                    @ApiImplicitParam(name = "discount_Interest_rate", value = "贴现利率", dataType = "Float", required = false),
                    @ApiImplicitParam(name = "providerProductBalance", value = "供应商供货余额", dataType = "Float", required = false),
            }
    )
    public Object add(@Validated Purchase purchase) throws NoPermissionException {
        if (!CustomerUtil.validEditPermission(purchase.getCustomerCompanyId())) {
            throw new NoPermissionException();
        }
        purchaseService.insert(purchase);
        return SUCCESS_TIP;
    }

    /**
     * 删除采购配套
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    @Permission(Const.ADMIN_NAME)
    public Object delete(@RequestParam Integer purchaseId) {
        purchaseService.deleteById(purchaseId);
        return SUCCESS_TIP;
    }

    /**
     * 修改采购配套
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    @Permission
    public Object update(@Validated Purchase purchase) throws NoPermissionException {
        Purchase dbPur = this.purchaseService.selectById(purchase.getId());
        if (dbPur == null) {
            return new GunsException(BizExceptionEnum.REQUEST_NULL);
        }
        if(!CustomerUtil.validEditPermission(dbPur.getCustomerCompanyId())){
            throw new NoPermissionException();
        }
        purchaseService.updateById(purchase);
        return SUCCESS_TIP;
    }

    @RequestMapping(value = "/purchase_detail/{customerCompanyId}")
    public Object toDetail(@PathVariable("customerCompanyId") Integer customerCompanyId, Model model) {
        List<Map<String, Object>> list = purchaseDao.selectByCompanyId(customerCompanyId);
        model.addAttribute("items", new PurchaseWrapper(list).warp());
        return PREFIX + "purchase_detail.html";
    }

    /**
     * 采购配套详情
     */
    @RequestMapping(value = "/detail/{purchaseId}")
    @ResponseBody
    @ApiOperation(value = "更新采购配套", tags = "采购配套", httpMethod = "POST", code = 200, response = SuccessTip.class)
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name = "id", value = "id", dataType = "integer", required = true),
                    @ApiImplicitParam(name = "year", value = "年度", dataType = "int", required = true),
                    @ApiImplicitParam(name = "providerName", value = "供应商名称", dataType = "string", required = true),
                    @ApiImplicitParam(name = "customerCompanyId", value = "客户id", dataType = "integer", required = true),
                    @ApiImplicitParam(name = "product", value = "product", dataType = "string", required = true),
                    @ApiImplicitParam(name = "annualPurchaseAmount", value = "年度采购金额", dataType = "Float", required = true),
                    @ApiImplicitParam(name = "accountPayableBalance", value = "应付账款余额", dataType = "Float", required = false),
                    @ApiImplicitParam(name = "cashPaid", value = "现金付款量", dataType = "Float", required = false),
                    @ApiImplicitParam(name = "silverTicketPaid", value = "银票付款量", dataType = "Float", required = false),
                    @ApiImplicitParam(name = "businessTicketPaid", value = "商票付款量", dataType = "Float", required = false),
                    @ApiImplicitParam(name = "period", value = "一般期限", dataType = "Float", required = false),
                    @ApiImplicitParam(name = "businessTicketDiscount", value = "商票贴现量", dataType = "Float", required = false),
                    @ApiImplicitParam(name = "discount_Interest_rate", value = "贴现利率", dataType = "Float", required = false),
                    @ApiImplicitParam(name = "providerProductBalance", value = "供应商供货余额", dataType = "Float", required = false),
            }
    )
    public Object detail(@PathVariable("purchaseId") Integer purchaseId) {
        Purchase purchase = purchaseService.selectById(purchaseId);
        if (purchase == null) {
            throw new GunsException(BizExceptionEnum.DB_RESOURCE_NULL);
        }

        Map<String, Object> map = BeanKit.beanToMap(purchase);
        if (CustomerUtil.validEditPermission(purchase.getCustomerCompanyId())) {
            map.put(Const.AUTHORITY_FIELD_NAME, 1);
        }else{
            map.put(Const.AUTHORITY_FIELD_NAME, -1);
        }
        return new PurchaseWrapper(map).warp();
    }

    /**
     * 导出Excel模板
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/exportXlsByM", headers = {"Accept=application/vnd.ms-excel"})
    public String exportXlsByT(HttpServletRequest request, HttpServletResponse response
            , DataGrid dataGrid, ModelMap modelMap) {
        modelMap.put(NormalExcelConstants.FILE_NAME, "采购配套模板");
        modelMap.put(NormalExcelConstants.CLASS, PurchaseXlsM.class);
        modelMap.put(NormalExcelConstants.PARAMS, new ExportParams("采购配套列表",
                "导出信息"));
        modelMap.put(NormalExcelConstants.DATA_LIST, PurchaseXlsM.example());
        return NormalExcelConstants.EASYPOI_EXCEL_VIEW;
    }


    @RequestMapping(method = RequestMethod.POST, path = "/importExcel")
    @ResponseBody
    public Object importExcel(MultipartHttpServletRequest multipartHttpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        Map<String, MultipartFile> multipartFileMap = multipartHttpServletRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : multipartFileMap.entrySet()) {
            MultipartFile file = entity.getValue();//获取文件上传对象
            ImportParams params = new ImportParams();
            //标题行数
            params.setTitleRows(1);
            //表头行数
            params.setHeadRows(1);
            //是否需要保存上传的EXCEL
            params.setNeedSave(false);
            List<PurchaseXlsM> result = ExcelImportUtil.importExcel(file.getInputStream(), PurchaseXlsM.class, params);
            VlidationUtil.validateList(result);
            purchaseService.insertXlsListPurchase(result);
        }
        return "文件导入成功";
    }
}
